# -*- coding:utf-8 -*-
import yaml
import psutil
from os import getenv, access, F_OK, name, mkdir, path
import getpass
from sys import executable, exit


def GetSystemDevice():
    SystemDevice = getenv('SystemDrive')
    if access(f"{SystemDevice}/Windows", F_OK):
        pass
    else:
        for x in psutil.disk_partitions():
            try:
                access(f"{x[1]}Windows", F_OK)
            except FileNotFoundError:
                pass
            else:
                SystemDevice = x[1]
                break
    return SystemDevice


# 设置AppData存放位置
def GetAppDataDir():
    if name == 'nt':
        if getenv('APPDATA'):
            AppDataDir = f"{getenv('APPDATA')}/"
            if access(f"{AppDataDir}EasyPython", F_OK):
                AppDataDir = f"{getenv('APPDATA')}/EasyPython"
            else:
                mkdir(f"{AppDataDir}EasyPython")
                AppDataDir = f"{getenv('APPDATA')}/EasyPython"
        else:
            AppDataDir = f"{GetSystemDevice()}User/{getpass.getuser()}/AppData/Roaming/"
            if access(f"{AppDataDir}EasyPython", F_OK):
                AppDataDir = f"{getenv('APPDATA')}/EasyPython"
            else:
                mkdir(f"{AppDataDir}EasyPython")
                AppDataDir = f"{getenv('APPDATA')}/EasyPython"

    else:
        if getenv('HOME'):
            AppDataDir = f"{getenv('HOME')}/.config/"
            if access(f"{AppDataDir}EasyPython", F_OK):
                AppDataDir = f"{getenv('HOME')}/.config/EasyPython"
            else:
                mkdir(f"{AppDataDir}EasyPython")
                AppDataDir = f"{getenv('HOME')}/.config/EasyPython"
        else:
            AppDataDir = f"/home/{getpass.getuser()}/.config/"
            if access(f"{AppDataDir}EasyPython", F_OK):
                AppDataDir = f"{getenv('HOME')}/.config/EasyPython"
            else:
                mkdir(f"{AppDataDir}EasyPython")
                AppDataDir = f"{getenv('HOME')}/.config/EasyPython"
    return AppDataDir


def LoadOrCreatConfigFile():
    if access(f"{GetAppDataDir()}/config.yml", F_OK):
        config = yaml.safe_load(
            open(f"{GetAppDataDir()}/config.yml", encoding="utf-8").read())
    else:
        print("Config File Not Found, Creating.")
        with open(f"{GetAppDataDir()}/config.yml", 'w',
                  encoding="utf-8") as f1:
            with open(f"{GetInstallDir()}/EasyScript/config.yml",
                      encoding="utf-8") as f2:
                f1.write(f2.read())
        config = yaml.safe_load(
            open(f"{GetAppDataDir()}/config.yml", encoding="utf-8").read())
    return config


def LoadOrCreatConfigFile_debug():
    if access(f"{GetAppDataDir()}/config.yml", F_OK):
        config = yaml.safe_load(
            open(f"{GetAppDataDir()}/config.yml", encoding="utf-8").read())
    else:
        print("Config File Not Found, Creating.")
        with open(f"{GetAppDataDir()}/config.yml", 'w',
                  encoding="utf-8") as f1:
            # with open(f"{GetInstallDir()}/EasyScript/config.yml", encoding="utf-8") as f2:
            #     f1.write(f2.read())
            with open("EasyScript/config.yml", encoding="utf-8") as f2:
                f1.write(f2.read())
        config = yaml.safe_load(
            open(f"{GetAppDataDir()}/config.yml", encoding="utf-8").read())
    return config


def WriteConfigFile(Data):
    with open(f"{GetAppDataDir()}/config.yml", 'w', encoding="utf-8") as f:
        f.write(yaml.dump(Data))


def GetInstallDir():
    return path.split(executable)[0]


def CheckFileUpdate():
    if access(f"{GetAppDataDir()}/config.yml", F_OK):
        config_old = yaml.safe_load(open(f"{GetAppDataDir()}/config.yml", encoding="utf-8").read())
    else:
        return False
    if access(f"{GetInstallDir()}/EasyScript/config.yml", F_OK):
        config_new = yaml.safe_load(open(f"{GetInstallDir()}/EasyScript/config.yml", encoding="utf-8").read())
    else:
        return False
    if str(config_old['options']['majar-version']) != str(config_new['options'][
            'majar-version']) or str(config_old['options'][
                'minor-version']) != str(config_new['options'][
                    'minor-version']) or str(config_old['options'][
                        'patch-version']) != str(config_new['options'][
                            'patch-version']):
        print("Updating Config File.... Don't turn off the program.")
        WriteConfigFile(config_new)
        print("Done. Please restart the program.")
        exit()
    else:
        return False


def CheckFileUpdate_debug():
    if access(f"{GetAppDataDir()}/config.yml", F_OK):
        config_old = yaml.safe_load(open(f"{GetAppDataDir()}/config.yml", encoding="utf-8").read())
    else:
        return False
    if access("EasyScript/config.yml", F_OK):
        config_new = yaml.safe_load(open("EasyScript/config.yml", encoding="utf-8").read())
    else:
        return False
    if str(config_old['options']['majar-version']) != str(config_new['options'][
            'majar-version']) or str(config_old['options'][
                'minor-version']) != str(config_new['options'][
                    'minor-version']) or str(config_old['options'][
                        'patch-version']) != str(config_new['options'][
                            'patch-version']):
        print("Updating Config File.... Don't turn off the program.")
        WriteConfigFile(config_new)
        print("Done. Please restart the program.")
        exit()
    else:
        return False
